<template>
    <DialogCom :draggable="true" :title="title" :width="'500'" :visible="isVisible" @close="close" @confirm="confirm">
        <template v-slot:content>
            <div class="base-items">
                <span>数据集：</span>
                <el-select v-model="currentdataset" placeholder="请选择数据集" class="items-width-large">
                    <el-option v-for="(item, index) in datasets" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
            </div>
            <div class="dataset-content">
                <div class="xbsj-table">
                    <el-table :data="textureList" ref="table" border :cell-style="cellStyle2"
                        :header-cell-style="cellStyleSmall" @current-change="currentChange" highlight-current-row
                        :max-height="285">
                        <el-table-column type="index" label="序号" width="80" align="center"
                            :show-overflow-tooltip="true" />
                        <el-table-column prop="oss" label="名称" :show-overflow-tooltip="true" />
                        <el-table-column label="缩略图" width="200">
                            <template #default="scope">
                                <img :src="scope.row.oss ? `${cimrtsIpRef}/ds/featuretiles/${currentdataset}/${scope.row.oss}` : require('@/assets/no-img.png')"
                                    alt="">
                            </template>
                        </el-table-column>


                    </el-table>
                </div>
                <div class="bottom">
                    <PaginatorCom :currentPage="pages.pageNum" :pageSize="pages.pageSize" :total="total"
                        @update:currentPage="handleCurrentChange" @update:pageSize="handleSizeChange" />
                </div>
            </div>
        </template>
    </DialogCom>

    <TooltipCom v-if="currentDialog == 'clone'" :content="`当前选择纹理不存在于数据集 ${datasetName} 中，是否克隆？`" :title="'克隆'"
        :isVisible="true" @close="currentDialog = ''" @confirm="cloneConfirm" />
</template>
<script setup lang="ts">
import DialogCom from "@/components/common/DialogCom.vue";
import { watch, ref, onBeforeUnmount, onMounted, nextTick } from "vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import {
    createVueDisposer,
    toVR,
} from "earthsdk-ui";
import { cellStyle, headCellStyle, cellStyleSmall, cellStyle2, } from "@/scripts/tableStyle";
import PaginatorCom from '@/components/common/PaginatorCom.vue';
import { WaterMend } from "@/scripts/cimrtsManager/waterMend";
import TooltipCom from "@/components/common/TooltipCom.vue";
import { reqCloneTexture } from "@/api";
import { ElMessage } from "element-plus";
import loading from "@/api/loading";

const props = defineProps({
    isVisible: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: "",
    },
    datasetName: {
        type: String,
        default: "",
    },
    url: {
        type: String,
        default: "",
    },
});

const emits = defineEmits(["close", "confirm"]);

const currentDialog = ref("");

const d = createVueDisposer(onBeforeUnmount);
const cimrtsManager = getProjectManager().cimrtsManager;

const waterMend = cimrtsManager.waterMend as WaterMend

const pages = ref({
    pageNum: 1,
    pageSize: 5,
})
const total = ref(0)

// cimrts服务ip
const cimrtsIpRef = toVR(d, [cimrtsManager, "cimrtsIp"]);
// 材质列表
const textureList = ref<any>([])

const currentdataset = ref(props.datasetName)
const datasets = cimrtsManager.tileServiceInfo.datasets

watch(currentdataset, async () => {
    if (!currentdataset.value) return;
    await listReqest()
})


const idname = ref("")
const id = ref("")



const currentChange = (item: any) => {
    if (!item) {
        idname.value = ""
        id.value = ""
        return;
    }
    idname.value = item.oss
    id.value = item.id
}

/**
 * 监听当前页数变化
 * @param {number} val 
 */
const handleCurrentChange = (val: number) => {
    pages.value.pageNum = val;
    listReqest()
}
/**
 * 监听当前页条数变化
 * @param {number} val 
 */
const handleSizeChange = (val: number) => {
    pages.value.pageSize = val;
    listReqest()
}

// 关闭按钮
const close = () => {
    emits('close')
}
// 确认
const confirm = async () => {
    if (!idname.value) {
        ElMessage.error("请选择纹理")
        return
    }
    if (props.datasetName == currentdataset.value) {
        emits('confirm', idname.value, currentdataset.value)
    } else {
        currentDialog.value = 'clone'
    }
}

const table = ref<any>(null)

const listReqest = async () => {
    const param = {
        datasetName: currentdataset.value,
        ...pages.value,
    }
    // 获取材质列表
    const res = await waterMend.getTextureList(param) as any
    textureList.value = res.tableData
    total.value = res.total
}

// 是否克隆
const cloneConfirm = async () => {
    try {
        const param = {
            "sourceDatasetName": currentdataset.value,
            "targetDatasetName": props.datasetName,
            "ossId": idname.value
        }
        const res = await reqCloneTexture(param)
        // @ts-ignore
        if (res.status == "ok") {
            loading.closeLoading()
            ElMessage.success("克隆成功")
            emits('confirm', idname.value, currentdataset.value)
        } else {
            ElMessage.error("克隆失败")
            loading.closeLoading()
        }
    } catch (error) {
        ElMessage.error("克隆失败")
        loading.closeLoading()
        console.error(error)
    }
}

onMounted(async () => {
    if (props.url) {
        const param = {
            datasetName: currentdataset.value,
            pageNum: 1,
            pageSize: 100000000,
        }
        // 获取材质列表
        const res = await waterMend.getTextureList(param) as any
        // 高亮当前行
        const index = res.tableData.findIndex((item: any) => item.oss == props.url)
        pages.value.pageNum = index ? Math.ceil((index + 1) / Number(pages.value.pageSize)) : 1

    }
    await listReqest()

    setTimeout(() => {
        const index = textureList.value.findIndex((item: any) => item.oss == props.url)
        index != undefined && table.value.setCurrentRow(textureList.value[index])
    }, 200)
})
</script>

<style scoped>
.is-active {
    border: 1px solid #409eff;
}

.lib-content {
    display: flex;
    flex-wrap: wrap;
    gap: 20px 9px;
    height: 276px;
    overflow-y: auto;
}

.img-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.img {
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    padding: 10px;
}

.img img {
    width: calc(100%);
    height: calc(100%);
}

.name {
    width: 80px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 5px 0;
}

.select-table {
    height: calc(100% - 60px);
    display: flex;
    flex-direction: column;
    justify-content: space-between
}

.actived {
    color: #8383ff;
}

.source>span {
    cursor: pointer;
}

.dataset-content {
    display: flex;
    flex-direction: column;
    height: 340px;
    justify-content: space-between;
}

.xbsj-table {
    margin: 15px 0;
}

.bottom {
    display: flex;
    justify-content: center;
}

.el-table .cell img {
    height: 43px;
    width: 125px;
}

.base-items {
    display: grid;
    grid-template-columns: 70px 150px;
    align-items: center;
}
</style>